#!/bin/sh

url=https://www.internic.net/domain
base_dir=/usr/share/dns-root-hints
_tmp=$(mktemp -d -p .)

if [ $(id -u) != "0" ]; then
	echo "Needs to run as root."
	exit 1
fi

_check_sig() {
	local GNUPGHOME="$HOME/.gpg"
	install -d -m 0700 "$GNUPGHOME"
	gpg --import < $base_dir/verisign-grs-nstld-key.asc
	gpg --verify "${_tmp}/named.root.sig" "${_tmp}/named.root"
}

for file in named.root named.root.sig; do
	curl -sLR ${url}/${file} -o "${_tmp}/${file}" || exit 1
done

# compare new and current versions
_drh_new_ver=$(grep "related version of root zone:" ${_tmp}/named.root | egrep -o '[0-9]{10}')
_drh_current_ver=$(grep "related version of root zone:" $base_dir/named.root | egrep -o '[0-9]{10}')

# update to new version if needed
echo "Version $_drh_current_ver <- Installed"
echo "Version $_drh_new_ver <- Downloaded"

if [ "$_drh_new_ver" != "$_drh_current_ver" ]; then
	_check_sig || exit 1
	mv ${_tmp}/named.root $base_dir/named.root || exit 1
	mv ${_tmp}/named.root.sig $base_dir/named.root.sig || exit 1
	echo -e "\nZone file updated.\n"
else
	echo -e "\nZone file already up-to-date.\n"
fi

# cleanup
rm "${_tmp}"/* 2>/dev/null || true
rmdir "${_tmp}" 2>/dev/null || true

